<template>
  <el-form :model="form" ref="ruleFormRef" :label-position="labelPosition" label-width="120px" :inline="true"
    :rules="rules" status-icon class="demo-form-inline">
    <el-form-item label="标准名称:">
      <el-input  v-model="form.name" maxlength="19" placeholder="请输入"  :disabled="1"  />
    </el-form-item>
    <el-form-item label="标准代码:">
      <el-input  v-model="form.code" maxlength="19" placeholder="请输入"   :disabled="1"  />
    </el-form-item>
<!--    <el-form-item label="标准版本号:" prop="version">-->
<!--      <el-input  v-model="form.version" maxlength="19" placeholder="请输入"  />-->
<!--    </el-form-item>-->
    <el-form-item label="现处阶段:">
      <SelectOption :selectValue="form.currentStage" :options="data.currentStage" @change-value="changeValue2"  :disabled="1" > </SelectOption>
    </el-form-item>
    <el-form-item label="标准级别:">
      <SelectOption :selectValue="form.levelName" :options="data.orgAllList" @change-value="changeValue0"  :disabled="1" > </SelectOption>
    </el-form-item>
    <el-form-item label="标准类别:">
      <SelectOption :selectValue="form.classType" :options="data.typeOptions" @change-value="changeValue1"  :disabled="1" > </SelectOption>
      <!-- <el-input v-model="form.phone" maxlength="15" /> -->
    </el-form-item>

    <el-form-item  label="业务板块:">
      <SelectOption multiple
                    :selectValue="form.businessId"
                    lable-key="itemText"
                    value-key="itemValue"
                    :options="data.business"
                    @change-value="changeValue3"  :disabled="1" >
      </SelectOption>
    </el-form-item>

    <el-form-item label="参编情况:">
      <SelectOption :selectValue="form.editCondition" :options="data.editCondition" @change-value="changeValue4"  :disabled="1" > </SelectOption>
    </el-form-item>
    <el-form-item label="立项时间:">
      <el-date-picker v-model="form.projectApprovalDate" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable
        @change="handleChangeDate"  :disabled="1"  />
    </el-form-item>

    <el-form-item label="发布时间:">
      <el-date-picker v-model="form.publicDate" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable
        @change="handleChangeDate1"  :disabled="1"  />
    </el-form-item>

<!--    <el-form-item label="生效日期:" prop="effectDate">-->
    <el-form-item label="生效日期:" >
      <el-date-picker v-model="form.effectDate" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable
        @change="handleChangeDate2"  :disabled="1"  />
    </el-form-item>

    <el-form-item label="失效日期:">
      <el-date-picker v-model="form.failureDate" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable
        @change="handleChangeDate3"   :disabled="1" />
    </el-form-item>
    <el-form-item label="开始时间:" prop="startDate">
      <el-date-picker v-model="form.startDate" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable
        @change="handleChangeDate4"  :disabled="1"  />
    </el-form-item>
    <el-form-item label="结束时间:"  prop="endDate">
      <el-date-picker v-model="form.endDate" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable
        @change="handleChangeDate5"   :disabled="1" />
    </el-form-item>
    <!-- <el-form-item label="中咨承担单位:" label-width="100px" style="width: 30%" prop="undertakeUnit">
      <SelectOption :selectValue="form.undertakeUnit" :options="data.constructSelect" @change-value="changeValue5"> </SelectOption>
    </el-form-item> -->
    <el-form-item label="中咨承担单位:">
      <popup-tree-input
        :data="data.popupTreeData"
        :props="data.popupTreeProps"
        :prop="
        deptForm.parentName == null
        ? $t('message.org.top_menu')
        : form.undertakeUnit
        "
        node-key="id"
        :current-change-handle="handleTreeSelectChange"  :disabled="1"
      />
    </el-form-item>

<!--    <el-form-item label="项目负责人:" prop="projectChangerName">-->
<!--      <el-input v-model="form.projectChangerName" />-->
<!--    </el-form-item>-->
    <el-form-item label="联系人:" >
<!--    <el-form-item label="联系人:" prop="contact">-->
      <!-- <SelectOption :selectValue="form.contact" :options="data.stateSelect" @change-value="changeValue6">
      </SelectOption> -->
      <user-list-modal
        v-model="form.contact"
        @update:modelValue="changeValue6"
        :default-users="[]"
        :multiple="false"
        :devType="'platform'"  :disabled="1"
      />
    </el-form-item>

    <el-form-item label="管理机构:">
      <el-input v-model="form.managerUnit" placeholder="标准组织单位"    :disabled="1" />
    </el-form-item>
    <el-form-item label="署名单位:">
      <!-- <SelectOption :selectValue="form.renameUnit" :options="data.constructSelect" @change-value="changeValue7"> </SelectOption> -->
      <popup-tree-input
        :default-checked-key="form.renameUnitId ? form.renameUnitId.split(',') : []"
        :show-checkbox="true"
        :data="data.popupTreeData"
        :props="data.popupTreeProps"
        :prop="
            deptForm.parentName == null
            ? $t('message.org.top_menu')
            : form.renameUnit
          "
        node-key="id"
        :change-handle="changeValue7"  :disabled="1"
      />
    </el-form-item>
    <el-form-item label="署名排名:" placeholder="请输入">
      <el-input  oninput="value=value.replace(/^0|[^0-9]/g,'')" type="number"  placeholder="请输入"  v-model="form.renameRank"   :disabled="1" />
    </el-form-item>

    <el-form-item label="专业方向:" >
      <el-input v-model="form.major"  placeholder="请输入"  :disabled="1"  />
    </el-form-item>
<!--
    <el-form-item label="署名单位" style="width: 100%" prop="renameUnit" >
      <div class="selectLabel">
        <el-tag v-for="tag in renameUnit" :key="tag" class="mx-1" closable @close="handleCloseUnit(tag)">
          {{ tag.value }}
        </el-tag>
      </div>
      <span class="addLabel" @click="addUnitBox">添加单位</span>
    </el-form-item>
-->
    <el-form-item label="考核要求:" class="labelHeight" style="width: 100%">
      <el-input v-model="form.checkRequirement" :autosize="{ minRows: 3 }" maxlength="1000" type="textarea" placeholder="请输入"   :disabled="1" />
    </el-form-item>

    <el-form-item label="主要工作内容:" class="labelHeight" style="width: 100%">
      <el-input v-model="form.mainWorkContent" :autosize="{ minRows: 3 }" maxlength="1000" type="textarea"
        placeholder="请输入"  :disabled="1"  />
    </el-form-item>

    <el-form-item label="简介:" class="labelHeight" style="width: 100%">
      <el-input v-model="form.intro" :autosize="{ minRows: 3 }" maxlength="1000" type="textarea" placeholder="请输入"   :disabled="1" />
    </el-form-item>
  </el-form>
</template>
<script lang="ts">
import * as proxy from '@/constants/proxy'
import request from '@/utils/request'
import UserListModal from '@/views/project/components/UserListModal/index.vue'
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import selectOptionDx from '@/views/science/components/selectOptionDx/index.vue'
import { onMounted, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
// import { getOrgTree } from '../../api/technicalNorms'
// import { string } from 'mathjs'
// import DictItem from '@/views/system/dict-manage/components/dictItem.vue'
export default {
  components: {
    SelectOption,
    PopupTreeInput,
    UserListModal,
  },
  emits: {
    valueFlag: null,
  },
  setup(props, { emit }) {
    const store = useStore()
    const labelPosition = ref('right')

    const deptForm = {
      parentId: 0,
      parentName: '',
    }
    const data = reactive({
      activeName: ref('first'),
      // 字典
      orgAllList:[],
      levelOptions:[],
      currentStage:[],
      business:[],
      editCondition:[],
      stateSelect:[],
      constructSelect:[],
      typeOptions:[],
      popupTreeProps: {
        label: 'name',
        children: 'children',
      },
      popupTreeData: [],
      dictCatalog: [],
      tableTreeData: [
        {
          children: [],
          // dictName: $i18n.t('message.dict.top'),
          dictName:'',
          id: undefined,
        },
      ],
      defaultExpandedKeys: [],
    })

    const form = reactive(store.state.technicalNorms.form)
    const pickerOptionsStart = (rule, value, callback) =>{
    if(value){
        if(new Date(form.startDate).getTime() > new Date(form.endDate).getTime()){
            return callback(new Error("开始时间不能大于结束时间"))
        }else{
              return callback()
            }
    }
}
    const pickerOptionsEnd = (rule, value, callback) => {
        if(value){
            if(new Date(form.startDate).getTime() >  new Date(form.endDate).getTime()){
                return callback(new Error("结束时间不能小于开始时间"))
            }else{
              return callback()
            }
        }
    }

    const value1 = ref('')

    watch(form, (newValue, oldValue) => {
      store.commit('technicalNorms/getForm', { ...form })
    });



    // 字典
    const affiliation = () => {
      request({
        url: proxy.CHECC_API_CMS + '/dictItem/codelist',
        method: 'post',
        data:["KJSL_STANDARD_LEVEL_CATEGORY","KJSL_PREPARATION_CATEGORY","KJSL_AT_PRESENT_STAGE","KJSL_PARTICIPATION_STATUS1","KJSL_BUSINESS_SECTOR","KJSL_STANDARD_LEVEL_CATEGORY"]

      }).then((res) => {
        data.orgAllList = res.data.data.KJSL_STANDARD_LEVEL_CATEGORY
        data.levelOptions = res.data.data.KJSL_PREPARATION_CATEGORY
        data.currentStage = res.data.data.KJSL_AT_PRESENT_STAGE
        data.business = res.data.data.KJSL_BUSINESS_SECTOR
        data.editCondition = res.data.data.KJSL_PARTICIPATION_STATUS1
      })
    }
    const changeValue0 = (item) => {
      form.levelName = item.itemText
      form.levelId = item.itemValue

      data.typeOptions = item.children
    }
    const changeValue1 = (item) => {
      form.classType = item.itemText
      form.classId = item.itemValue
    }
    const changeValue2 = (item) => {
      form.currentStage = item.itemText
      form.className = item.itemValue
    }
    const changeValue3 = (item) => {
      form.businessId = item.itemValue
      form.business = item.itemText
    }
    const changeValue4 = (item) => {
      form.editConditionId = item.itemValue
      form.editCondition = item.itemText
    }
    const changeValue5 = (item) => {
      form.rdDept = item.id
      form.rdDeptName = item.name
    }
    const changeValue6 = (item) => {
      form.contact = item.cname
      form.contactId = item.userId
    }
    const changeValue7 = (_, nodes) => {
      const names = nodes.checkedNodes.map(t => t.name) || [];
      const ids = nodes.checkedNodes.map(t => t.id) || [];
      form.renameUnit = names.join(',')
      form.renameUnitId = ids.join(',')

      // form.plaStatus = item.itemValue
      // form.plaStatusName = item.itemText
    }
    const findTreeData = async ()=>{

      return request({
                url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
                method: "get",
            }).then(res => {
                data.popupTreeData = res.data.data
            })
      // let res = await  getOrgTree()
      //   console.log(res,'////')
      //   data.dictCatalog = res.data.data
      //   data.tableTreeData = data.dictCatalog
      //   console.log(data.dictCatalog,'data.dictCatalogdata.dictCatalogdata.dictCatalog');
      //   // data.defaultExpandedKeys = data.dictCatalog.map((item) => item.id)
      //   //获取上级机构
      //   data.popupTreeData = res.data.data

        // data.constructSelect = res.data.data

    }
    const getParentMenuTree =(tableTreeDdata)=> {
      const parent = {
        parentId: 0,
        name: '顶级菜单',
        children: tableTreeDdata,
      }
      return [parent]
    }
    // 机构树选中
    const handleTreeSelectChange = (data)=> {
      form.undertakeUnitId = data.id
      form.undertakeUnit = data.name
      // undertakeUnit
      // undertakeUnitId
      // renameUnit
      // renameUnitId
    }

    const rules = reactive({
      name: [
        { required: true, message: '请输入标准名称', trigger: 'blur' },
      ],
      code: [
        { required: true, message: '请输入标准代码', trigger: 'blur', },
      ],
      version: [
        { required: true, message: '请输入标准版本号', trigger: 'blur', },
      ],
      levelName: [
        { required: true, message: '请选择标准级别', trigger: 'change', },
      ],
      classType: [
        { required: true, message: '请选择标准类别', trigger: 'change', },
      ],
      currentStage: [
        { required: true, message: '请选择现处阶段', trigger: 'change', },
      ],
      businessId: [
        { required: true, message: '请选择业务板块', trigger: 'change' },
      ],
      editCondition: [
        { required: true, message: '请选择参编情况', trigger: 'change' },
      ],
      projectApprovalDate: [
        { required: true, message: '请选择立项时间', trigger: 'change' },
      ],
      publicDate: [
        { required: true, message: '请选择发布时间', trigger: 'change' },
      ],
      effectDate: [
        { required: true, message: '请选择生效日期', trigger: 'change' },
      ],
      projectChangerName: [
        { required: true, message: '请输入项目负责人', trigger: 'blur' },
      ],
      contact: [
        { required: true, message: '请选择联系人', trigger: 'change' },
      ],
      managerUnit: [
        { required: true, message: '请输入管理机构', trigger: 'blur' },
      ],
      renameRank: [
        { required: true, message: '请选择署名排名', trigger: 'change' },
      ],
      renameUnit: [
        { required: true, message: '请选择署名单位', trigger: 'change' },
      ],
      undertakeUnit: [
        { required: true, message: '请选择', trigger: 'change,blur' },
      ],
      // startDate: [{  validator: pickerOptionsStart, trigger: "change" }],
      // endDate: [{ validator: pickerOptionsEnd, trigger: "change" }],
    })

    const ruleFormRef = ref()
    const submitForm = async () => {
      await ruleFormRef.value.validate((valid) => {
          console.log('valid!',valid)
        if (valid) {
          emit('valueFlag', true)
        } else {
          emit('valueFlag', false)
        }
      })
    }


    const handleChangeDate = (val) => {
      const year = val.getFullYear(); // 获取年份
      const month = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1); // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate(); // 获取日期
      const formattedDate = `${year}-${month}-${day}`;
      form.projectApprovalDate = formattedDate
      store.commit('technologyNorms/getForm', { ...form })
    }

    const handleChangeDate1 = (val) => {
      const year = val.getFullYear(); // 获取年份
      const month = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1); // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate(); // 获取日期
      const formattedDate = `${year}-${month}-${day}`;
      form.publicDate = formattedDate
      store.commit('technologyNorms/getForm', { ...form })
    }
    const handleChangeDate2 = (val) => {
      const year = val.getFullYear(); // 获取年份
      const month = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1); // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate(); // 获取日期
      const formattedDate = `${year}-${month}-${day}`;
      form.effectDate = formattedDate
      store.commit('technologyNorms/getForm', { ...form })
    }
    const handleChangeDate3 = (val) => {
      const year = val.getFullYear(); // 获取年份
      const month = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1); // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate(); // 获取日期
      const formattedDate = `${year}-${month}-${day}`;
      form.failureDate = formattedDate
      store.commit('technologyNorms/getForm', { ...form })
    }
    const handleChangeDate4 = (val) => {
      const year = val.getFullYear(); // 获取年份
      const month = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1); // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate(); // 获取日期
      const formattedDate = `${year}-${month}-${day}`;
      form.startDate = formattedDate
      store.commit('technologyNorms/getForm', { ...form })
    }

    const handleChangeDate5 = (val) => {
      const year = val.getFullYear(); // 获取年份
      const month = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1); // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate(); // 获取日期
      const formattedDate = `${year}-${month}-${day}`;
      form.endDate = formattedDate
      store.commit('technologyNorms/getForm', { ...form })
    }

    onMounted(() => {
      affiliation()
      findTreeData()
    });

    watch(() => form.levelId, (newValue, oldValue) => {
        // console.log('watch 已触发', newValue)
    })

    return {
      labelPosition,
      data,
      form,
      value1,
      rules,
      getParentMenuTree,
      findTreeData,
      submitForm,
      ruleFormRef,
      affiliation,
      handleChangeDate,
      handleChangeDate1,
      handleChangeDate2,
      handleChangeDate3,
      handleChangeDate4,
      handleChangeDate5,
      changeValue0,
      changeValue1,
      changeValue2,
      changeValue3,
      changeValue4,
      changeValue5,
      changeValue6,
      changeValue7,
      deptForm,
      handleTreeSelectChange
    }
  },
}
</script>
<style lang="scss" scoped>
.demo-form-inline .el-form-item {
  width: 30%;
}

:deep(.labelHeight .el-form-item__label) {
  line-height: 20px;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor.el-input__inner) {
  width: 100%;
}

:deep(.demo-form-inline .el-select) {
  width: 100%;
  margin: 0;
}

.el-select {
  width: 100%;
  margin: 0;
}

.selectLabel {
  width: 70%;
  min-height: 40px;
  line-height: 40px;
  padding: 0 15px;
  border: 1px solid #ccc;
  border-radius: 6px;
  display: inline-block;
}

.addLabel {
  display: inline-block;
  width: 120px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: #169bd5;
  border-radius: 6px;
  color: #fff;
  margin-left: 15px;
  margin-top: 6px;
  vertical-align: top;
}

.unitBox {
  width: 100%;
  margin: 30px 0;

  .title {
    padding: 15px 0;
    border-bottom: 1px solid #ccc;
  }

  .tagBox {
    line-height: 40px;
    margin-top: 15px;
    border: 1px solid #ccc;
    border-radius: 8px;
    padding: 10px 15px;
  }
}

.el-tag {
  margin-right: 10px;
}
</style>
